/*
 * Copyright IBM Corp. All Rights Reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

// Running TestApp:
// gradle runApp

package application.java;

import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Network;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;


public class App {

	private static final String CHANNEL_NAME = System.getenv().getOrDefault("CHANNEL_NAME", "mychannel");
	private static final String CHAINCODE_NAME = System.getenv().getOrDefault("CHAINCODE_NAME", "erc20cj");

	static {
		System.setProperty("org.hyperledger.fabric.sdk.service_discovery.as_localhost", "true");
	}

	// helper function for getting connected to the gateway
	public static Gateway connectAdmin() throws Exception{
		// Load a file system based wallet for managing identities.
		Path walletPath = Paths.get("/root/fabric/scripts/fabric-samples/test-network-k8s/build/application/wallet");
		Wallet wallet = Wallets.newFileSystemWallet(walletPath);
		// load a CCP
		// Path networkConfigPath = Paths.get("..", "..", "test-network", "organizations", "peerOrganizations", "org1.example.com", "connection-org1.yaml");
		Path networkConfigPath = Paths.get("/root/fabric/scripts/fabric-samples/test-network-k8s/build/application/gateways/org1_ccp.json");
		Gateway.Builder builder = Gateway.createBuilder();
		builder.identity(wallet, "testUser3").networkConfig(networkConfigPath).discovery(true);
		return builder.connect();
	}

	public static Gateway connectUser() throws Exception{
		// Load a file system based wallet for managing identities.
		Path walletPath = Paths.get("/root/fabric/scripts/fabric-samples/test-network-k8s/build/application/wallet");
		Wallet wallet = Wallets.newFileSystemWallet(walletPath);
		// load a CCP
		// Path networkConfigPath = Paths.get("..", "..", "test-network", "organizations", "peerOrganizations", "org1.example.com", "connection-org1.yaml");
		Path networkConfigPath = Paths.get("/root/fabric/scripts/fabric-samples/test-network-k8s/build/application/gateways/org1_ccp.json");
		Gateway.Builder builder = Gateway.createBuilder();
		builder.identity(wallet, "testUser4").networkConfig(networkConfigPath).discovery(true);
		return builder.connect();
	}

	public static void main(String[] args) throws Exception {
		// enrolls the admin and registers the user
		try {
			EnrollAdmin.main(null);
			RegisterUser.main(null);
		} catch (Exception e) {
			System.err.println(e);
		}

		// connect to the network and invoke the smart contract
		try (Gateway gateway = connectAdmin()) {

			// get the network and contract
			System.out.println("Get Network");
			Network network = gateway.getNetwork(CHANNEL_NAME);
			System.out.println("Get Contract");
			Contract contract = network.getContract(CHAINCODE_NAME);
			
			byte[] result;
			result = contract.evaluateTransaction("ClientAccountID");
			System.out.println("ClientId result: " + new String(result));
			
			// contract.submitTransaction("Transfer", "testUser4", "200");
			// System.out.println("*** Transfer_erc20 committed successfully");
		}
		catch(Exception e){
			System.err.println(e);
			System.exit(1);
		}


		// connect to the network and invoke the smart contract
		// try (Gateway gateway = connectUser()) {

		// 	// get the network and contract
		// 	System.out.println("Get Network");
		// 	Network network = gateway.getNetwork(CHANNEL_NAME);
		// 	System.out.println("Get Contract");
		// 	Contract contract = network.getContract(CHAINCODE_NAME);
			
		// 	byte[] result;

		// 	result = contract.evaluateTransaction("ClientAccountID");
		// 	System.out.println("ClientId result: " + new String(result));

		// 	result = contract.evaluateTransaction("ClientAccountBalance");
		// 	System.out.println("*** Balance:"+new String(result));
		// }
		// catch(Exception e){
		// 	System.err.println(e);
		// 	System.exit(1);
		// }
	}


	private static void ClientAccountID(Contract contract) throws Exception {
		
		byte[] result = contract.evaluateTransaction("ClientAccountID");
		System.out.println("result: " + new String(result));
	}

	private static void Approve(Contract contract) throws  Exception {

		contract.submitTransaction("Approve", "appuser_org1", "20");
		System.out.println("*** Approve committed successfully");
	}

	private static void Allowance(Contract contract) throws  Exception {
		// var commit = contract.newProposal("Allowance")
		// 	.addArguments("tom","Saptha")
		// 	.build()
		// 	.endorse()
		// 	.submitAsync();

		// var result = commit.getResult();
		// var oldOwner = new String(result);
		// System.out.println("*** Successfully submitted transaction to transfer result: " + oldOwner);
		// System.out.println("*** Waiting for transaction commit");

		// var status = commit.getStatus();
		// if (!status.isSuccessful()) {
		// 	throw new RuntimeException("Transaction " + status.getTransactionId() +
		// 			" failed to commit with status code " + status.getCode());
		// }
		System.out.println("*** Allowance committed successfully");
	}

	private static void Transfer_erc20(Contract contract) throws Exception {
		
		// System.out.println(contract.getChaincodeName());
		// var commit = contract.newProposal("Transfer")
		// 		.addArguments("Saptha","200")
		// 		.build()
		// 		.endorse()
		// 		.submitAsync();

		// var result = commit.getResult();
		// var oldOwner = new String(result, StandardCharsets.UTF_8);
		// System.out.println("*** Successfully submitted transaction to transfer result: " + oldOwner);
		// System.out.println("*** Waiting for transaction commit");

		// var status = commit.getStatus();
		// if (!status.isSuccessful()) {
		// 	throw new RuntimeException("Transaction " + status.getTransactionId() +
		// 			" failed to commit with status code " + status.getCode());
		// }
		contract.submitTransaction("Transfer", "testUser1", "200");
		System.out.println("*** Transfer_erc20 committed successfully");
	}

	private static void TransferFrom_erc20(Contract contract)throws Exception {
		// var commit = contract.newProposal("TransferFrom")
		// 		.addArguments("tom","Saptha","20")
		// 		.build()
		// 		.endorse()
		// 		.submitAsync();

		// var result = commit.getResult();
		// var oldOwner = new String(result, StandardCharsets.UTF_8);
		// System.out.println("*** Successfully submitted transaction to transfer result: " + oldOwner);
		// System.out.println("*** Waiting for transaction commit");

		// var status = commit.getStatus();
		// if (!status.isSuccessful()) {
		// 	throw new RuntimeException("Transaction " + status.getTransactionId() +
		// 			" failed to commit with status code " + status.getCode());
		// }
		contract.submitTransaction("TransferFrom", "testUser1", "appuser_org1", "20");
		System.out.println("*** TransferFrom_erc20 committed successfully");
	}
	
}
